import $ from "jquery"
import { IState, IFilterDetails, IUserProfile } from "../types"
import {
	STYLES,
	USER_DATA_STORAGE,
	CONSTANTS_STORAGE,
	REPORTS_STORAGE,
} from "../constants"
import {
	startModalAlert,
	getDataFromLocalStorage,
	saveDataToLocalStorage,
	// removeDataFromLocalStorage,
	handlerPriceTickers,
	getUserPropertyByExchange,
} from "../common"

export const initialState = {
	loading: false,
	loaded: false,
	error: null,
	messagePopup: { category: "", message: "" },
	currentCourses: [],
	fundingRates: [],
	spreads: [],
	userOrderStatuses: [
		{ unpaid: 0, exchange: "BN" },
		{ unpaid: 0, exchange: "HB" },
		{ unpaid: 0, exchange: "KX" },
		{ unpaid: 0, exchange: "BZ" },
		{ unpaid: 0, exchange: "GX" },
		{ unpaid: 0, exchange: "BT" },
		{ unpaid: 0, exchange: "PX" },
		{ unpaid: 0, exchange: "MG" },
		{ unpaid: 0, exchange: "KC" },
		{ unpaid: 0, exchange: "BG" },
		{ unpaid: 0, exchange: "CX" },
		{ unpaid: 0, exchange: "BX" },
	],
	reports: {
		reportSpotOrders: [],
		reportMerchantOrders: [],
		reportBalances: [],
		reportCost: [],
		reportStats: {
			monthStats: { sell: [], buy: [] },
			yearStatsV1: {
				sell: [],
				buy: [],
			},
			yearStatsV2: {
				sell: [],
				buy: [],
			},
			yearStatsV3: {
				sell: [],
				buy: [],
			},
		},
	},
	filterDetails: {
		activeExchange: "63039ac2956b2f07f0e56f12", // Binance
		advDetails: {},
		balanceDetails: {},
		orderDetails: {},
		itemDetails: {},
		checkboxStatus: false,
		orderCoin: "all",
		orderTradeType: "all",
		orderStatusType: "all",
		orderPayType: "all",
		orderExchange: "all",
		advActiveStatus: "all",
		properties: [
			{
				exchange: "Binance",
				exchangeId: "63039ac2956b2f07f0e56f12",
				fiat: "RUB",
				asset: "USDT",
				tradeType: "BUY",
				tickerAssetFiat: "",
				priceAssetFiat: "",
				tickerCurrencyUSDT: "",
				priceCurrencyUSDT: "",
				transAmount: "1000",
				payTypeList: ["RaiffeisenBankRussia", "PostBankRussia", "MTSBank"],
				quantityPages: "20",
				checkboxStatus: false,
				orderCoin: "all",
				orderTradeType: "all",
				orderStatusType: "all",
				orderPayType: "all",
				orderExchange: "all",
				advActiveStatus: "all",
			},
		],
	},
	userProfile: {
		auth: false,
		token: "",
		id: "",
		login: "",
		lang: "en",
		theme: "night", // or light
		status: "user",
		advSell: 82.93,
		subAccounts: [],
		userProperties: [
			{
				exchange: "Binance",
				exchangeId: "63039ac2956b2f07f0e56f12",
				exchangeUserId: "",
				userNickName: "",
				updateOrders: true,
				soundAlert: "Sound/newOrder.wav",
				dateApiKeys: 0,
				payTypeList: ["RaiffeisenBankRussia", "PostBankRussia", "MTSBank"],
				favorites: [],
				favoriteAdvs: {
					sellList: [],
					buyList: [],
				},
				p2pOrders: [],
				spotOrders: [],
				merchantOrders: [],
				merchantPayMethods: [],
				merchantAdvs: [],
				currentBalances: {
					p2pBalance: [],
					spotBalance: [],
					futBalance: [],
				},
			},
		],
	},
}

// универсальный обработчик разных значений для advDetails
const handlerAdvDetails = (
	state: IState,
	name: string,
	value: any
): any => {
	let currentAdv = state.filterDetails.advDetails
	if (value === "payMethod") return currentAdv

	const obj = {
		identifier: "",
		payId: null,
		payType: "",
		iconUrlColor: "",
		tradeMethodName: "",
		tradeMethodShortName: "",
		tradeMethodBgColor: "",
	}
	const advTradeMethods = state.filterDetails.advDetails.tradeMethods
	const userPayMethods = getUserPropertyByExchange(
		"merchantPayMethods",
		state.filterDetails.activeExchange,
		state.userProfile.userProperties
	)
	if (name === "payTypeRemove") {
		for (let i = 0; i < advTradeMethods.length; i++) {
			if (advTradeMethods[i].identifier === value)
				advTradeMethods.splice(i, 1)
		}
		currentAdv = getNewObjDetails(
			currentAdv,
			"tradeMethods",
			advTradeMethods
		)
	} else if (name === "tradeMethods") {
		if (advTradeMethods.length < 5) {
			for (let i = 0; i < userPayMethods.length; i++) {
				if (userPayMethods[i].id === Number(value)) {
					obj.payId = userPayMethods[i].id
					obj.identifier = userPayMethods[i].identifier
					obj.payType = userPayMethods[i].identifier
					obj.iconUrlColor = userPayMethods[i].iconUrlColor
					obj.tradeMethodName = userPayMethods[i].tradeMethodName
					obj.tradeMethodShortName = userPayMethods[i].tradeMethodShortName
					obj.tradeMethodBgColor = userPayMethods[i].tradeMethodBgColor
				}
			}
			advTradeMethods.push(obj) // вставляем в конец новый payMethod
			currentAdv = getNewObjDetails(currentAdv, name, advTradeMethods)
		}
	} else {
		currentAdv = getNewObjDetails(currentAdv, name, value)
	}
	return currentAdv
}

// обработчик orderItem
const handlerItems = (
	state: IState,
	itemDetails: any,
	itemFlag: string
) => {
	const list = state.reports.reportMerchantOrders
	for (let i = 0; i < list.length; i++) {
		if (list[i].orderId === itemDetails.orderId) {
			list[i].payMethodName = itemDetails.payMethodName
			list[i].payMerchantAccount = itemDetails.payMerchantAccount
		}
	}
	return list
}

// универсальный обработчик разных значений select/input'ов для filterDetails
const handlerFilterDetails = (
	state: IState,
	exchange: string,
	name: string,
	value: any
): IFilterDetails => {
	let obj = state.filterDetails
	const properties: any = state.filterDetails.properties
	const arr = getUserPropertyByExchange(
		"payTypeList",
		exchange,
		properties
	).slice()

	// для полей state.filterDetails.properties
	if (exchange !== "") {
		const resultProps = handlerProperties(
			exchange,
			properties,
			arr,
			name,
			value
		)
		obj = { ...obj, properties: resultProps }
	}
	// для поля state.filterDetails.activeExchange
	else obj = getNewObjDetails(obj, name, value)

	return obj
}

// универсальный обработчик значений для userProfile
const handlerUserProfile = (
	state: IState,
	exchange: string,
	name: string,
	value: any
): IUserProfile => {
	let obj = state.userProfile
	const properties: any = state.userProfile.userProperties
	const arrUserFavorites = getUserPropertyByExchange(
		"favorites",
		exchange,
		properties
	).slice()

	// для полей state.userProfile.userProperties
	if (exchange !== "") {
		const resultProps = handlerProperties(
			exchange,
			properties,
			arrUserFavorites,
			name,
			value
		)
		obj = { ...obj, userProperties: resultProps }
	}
	// для всех остальных полей - lang, theme
	else obj = getNewObjDetails(obj, name, value)

	// сохраняем в LS
	saveDataToLocalStorage(USER_DATA_STORAGE, obj)
	return obj
}

// универсальный переборщик любых свойств filterDetails и userProfile
const getNewObjDetails = (
	obj: any,
	keyName: string,
	value: string
): any => {
	// перебираем свойства obj и при совпадении имён полей
	// присваиваем полю новое значение value
	for (const key in obj) {
		if (key === keyName) {
			obj[key] = value
		}
	}
	return obj
}

// универсальный обработчик filterDetails.properties и userProfile.properties
const handlerProperties = (
	exchange: string,
	properties: any,
	arrProps: any,
	name: string,
	value: any
) => {
	for (let i = 0; i < properties.length; i++) {
		if (
			properties[i].exchange === exchange ||
			properties[i].exchangeId === exchange
		) {
			// change userProfile.properties[i].payTypeList
			if (name === "userPayTypeList") {
				properties[i].payTypeList = value
			}
			// add item userProfile.properties[i].favorites
			else if (name === "addItemFavorites") {
				arrProps.push(value)
				properties[i].favorites = arrProps
			}
			// remove item userProfile.properties[i].favorites
			else if (name === "removeItemFavorites") {
				for (let j = 0; j < arrProps.length; j++) {
					if (arrProps[j].userId === value) {
						// вырезаем элемент
						arrProps.splice(j, 1)
						properties[i].favorites = arrProps
					}
				}
			} else properties[i][name] = value
		}
	}
	return properties
}

// обработчик изменения статуса объявления
const changeAdvStatus = (
	exchange: string,
	advs: any,
	arrayAdvNumbers: string[],
	advStatus: number
): any => {
	const arr = advs.slice()
	for (let i = 0; i < arr.length; i++) {
		if (exchange === "Binance" && arr[i].advNo === arrayAdvNumbers[0])
			arr[i].advStatus = advStatus
		else if (exchange === "Pexpay" && arr[i].adNo === arrayAdvNumbers[0])
			arr[i].adStatus = advStatus
	}
	return arr
}

// обновление статистических данных об избранном юзере
const updateFavorites = (state: any, details: any) => {
	const properties = state.userProfile.userProperties
	const exchange = state.filterDetails.activeExchange
	const favorites = getUserPropertyByExchange(
		"favorites",
		exchange,
		properties
	).slice()
	for (let i = 0; i < properties.length; i++) {
		if (properties[i].exchange === "Binance") {
			for (let j = 0; j < favorites.length; j++) {
				if (favorites[j].userId === details.userDetailVo.userNo) {
					favorites[j].authentication = details.userDetailVo.businessStatus
					favorites[j].emailVerified = details.userDetailVo.emailVerified
					favorites[j].bindMobile = details.userDetailVo.bindMobile
					favorites[j].idVerified = details.userDetailVo.kycVerified
					favorites[j].onlineStatus = details.userDetailVo.onlineStatus
					favorites[j].registerDays =
						details.userDetailVo.userStatsRet.registerDays
					favorites[j].firstOrderDays =
						details.userDetailVo.userStatsRet.firstOrderDays
					favorites[j].avgReleaseTimeOfLatest30day =
						details.userDetailVo.userStatsRet.avgReleaseTimeOfLatest30day
					favorites[j].avgPayTimeOfLatest30day =
						details.userDetailVo.userStatsRet.avgPayTimeOfLatest30day
					favorites[j].finishRateLatest30day =
						details.userDetailVo.userStatsRet.finishRateLatest30day
					favorites[j].completedOrderNumOfLatest30day =
						details.userDetailVo.userStatsRet.completedOrderNumOfLatest30day
					favorites[j].completedBuyOrderNumOfLatest30day =
						details.userDetailVo.userStatsRet.completedBuyOrderNumOfLatest30day
					favorites[j].completedSellOrderNumOfLatest30day =
						details.userDetailVo.userStatsRet.completedSellOrderNumOfLatest30day
					favorites[j].completedOrderTotalBtcAmountOfLatest30day =
						details.userDetailVo.userStatsRet.completedOrderTotalBtcAmountOfLatest30day
					favorites[j].completedOrderNum =
						details.userDetailVo.userStatsRet.completedOrderNum
					favorites[j].completedBuyOrderNum =
						details.userDetailVo.userStatsRet.completedBuyOrderNum
					favorites[j].completedSellOrderNum =
						details.userDetailVo.userStatsRet.completedSellOrderNum
					favorites[j].completedBuyOrderTotalBtcAmount =
						details.userDetailVo.userStatsRet.completedBuyOrderTotalBtcAmount
					favorites[j].completedSellOrderTotalBtcAmount =
						details.userDetailVo.userStatsRet.completedSellOrderTotalBtcAmount
					favorites[j].completedOrderTotalBtcAmount =
						details.userDetailVo.userStatsRet.completedOrderTotalBtcAmount
				}
			}
			properties[i].favorites = favorites
			properties[i].favoriteAdvs = {
				sellList: details.sellList,
				buyList: details.buyList,
				nickName: details.userDetailVo.nickName,
				merchantStatus: details.userDetailVo.userIdentity,
			}
		}
	}
	return properties
}

// активация вкладки главной страницы
const setActiveMainPage = () => {
	// получаем коллекцию дочерних элементов
	const elems = $("#pills-tabContent").children()
	// удаляем активный статус
	for (let i = 0; i < elems.length; i++) {
		$(elems[i]).removeClass("show active")
	}
	// активируем вкладку главной страницы
	$(elems[0]).addClass("show active")
}

// сохранение user payTypeList в filterDetails payTypeList
const getModifiedPayTypeDetails = (
	userproperties: any,
	filterdetails: any
) => {
	for (let i = 0; i < filterdetails.properties.length; i++) {
		filterdetails.properties[i].payTypeList = userproperties[i].payTypeList
	}
	return filterdetails
}

export const Reducer = (state: IState = initialState, action: any) => {
	switch (action.type) {
		case "LOAD_REQUESTED_DATA_ACTION":
			return {
				...state,
				loading: true,
				loaded: false,
			}

		case "LOAD_FAILURE_DATA_ACTION":
			startModalAlert()
			return {
				...state,
				loading: false,
				loaded: true,
				error: action.result.error,
				messagePopup: {
					category: STYLES.ERROR,
					message: action.result.message,
				},
			}

		case "GET_P2P_ORDERS_ACTION":
			if (action.result.success) {
				const tickers = action.result.data.tickers
				// получаение существующего хранилища констант
				const dataConstants = getDataFromLocalStorage(CONSTANTS_STORAGE)
				// сохранение изменвшихся полей хранилища констант
				saveDataToLocalStorage(CONSTANTS_STORAGE, {
					...dataConstants,
					tickers,
				})
				const exchangeName = action.exchange
				const { properties } = state.filterDetails
				const { userProperties } = state.userProfile
				const tickerAssetFiat = getUserPropertyByExchange(
					"tickerAssetFiat",
					exchangeName,
					properties
				)
				const tickerCurrencyUSDT = getUserPropertyByExchange(
					"tickerCurrencyUSDT",
					exchangeName,
					properties
				)
				const priceAssetFiat = handlerPriceTickers(tickerAssetFiat, tickers)
				const priceCurrencyUSDT = handlerPriceTickers(
					tickerCurrencyUSDT,
					tickers
				)
				const propsByPriceAssetFiat = handlerProperties(
					exchangeName,
					properties,
					[],
					"priceAssetFiat",
					priceAssetFiat
				)
				const propsByPriceCurrencyUSDT = handlerProperties(
					exchangeName,
					propsByPriceAssetFiat,
					[],
					"priceCurrencyUSDT",
					priceCurrencyUSDT
				)
				const userData = {
					...state.userProfile,
					userProperties: handlerProperties(
						exchangeName,
						userProperties,
						[],
						"p2pOrders",
						action.result.data.p2pOrders
					),
				}
				// сохраняем измененные данные в LS
				saveDataToLocalStorage(USER_DATA_STORAGE, userData)
				// startModalAlert()
				return {
					...state,
					loading: false,
					loaded: true,
					messagePopup: {
						category: STYLES.SUCCESS,
						message: action.result.message,
					},
					userProfile: userData,
					// currentCourses: action.result.data.tickers,
					filterDetails: {
						...state.filterDetails,
						properties: propsByPriceCurrencyUSDT,
					},
				}
			} else {
				startModalAlert()
				return {
					...state,
					messagePopup: {
						category: STYLES.ERROR,
						message: action.result.message,
					},
					loading: false,
					loaded: true,
				}
			}

		case "GET_MERCHANT_ORDERS_ACTION":
			if (action.result.success) {
				const exchangeName = action.exchange
				const { userProperties } = state.userProfile
				const userData = {
					...state.userProfile,
					userProperties:
						action.result.data.length === 0
							? userProperties
							: handlerProperties(
									exchangeName,
									userProperties,
									[],
									"merchantOrders",
									action.result.data
							  ),
				}
				// сохраняем измененные данные в LS
				saveDataToLocalStorage(USER_DATA_STORAGE, userData)
				startModalAlert()
				return {
					...state,
					userProfile: userData,
					messagePopup: {
						category: STYLES.SUCCESS,
						message: action.result.message,
					},
					loading: false,
					loaded: true,
				}
			} else {
				startModalAlert()
				return {
					...state,
					messagePopup: {
						category: STYLES.ERROR,
						message: action.result.message,
					},
					loading: false,
					loaded: true,
				}
			}

		case "GET_MERCHANT_ADVS_ACTION":
			if (action.result.success) {
				const exchangeName = action.exchange
				const { userProperties } = state.userProfile
				const propsByMerchantAdvs = handlerProperties(
					exchangeName,
					userProperties,
					[],
					"merchantAdvs",
					action.result.data.merchantAdvs
				)
				const userData = {
					...state.userProfile,
					userProperties: handlerProperties(
						exchangeName,
						propsByMerchantAdvs,
						[],
						"merchantPayMethods",
						action.result.data.userPayMethods
					),
				}
				// сохраняем измененные данные в LS
				saveDataToLocalStorage(USER_DATA_STORAGE, userData)
				startModalAlert()
				return {
					...state,
					messagePopup: {
						category: STYLES.SUCCESS,
						message: action.result.message,
					},
					userProfile: userData,
					loading: false,
					loaded: true,
				}
			} else {
				startModalAlert()
				return {
					...state,
					messagePopup: {
						category: STYLES.ERROR,
						message: action.result.message,
					},
					loading: false,
					loaded: true,
				}
			}

		case "SPOT_ORDERS_HISTORY_ACTION":
			startModalAlert()
			return {
				...state,
				messagePopup: {
					category: STYLES.SUCCESS,
					message: action.result.message,
				},
				loading: false,
				loaded: true,
			}

		case "SPOT_ORDERS_ACTIVE_ACTION":
			if (action.result.success) {
				const exchangeName = action.exchange
				const { userProperties } = state.userProfile
				const propsBySpotOrders = handlerProperties(
					exchangeName,
					userProperties,
					[],
					"spotOrders",
					action.result.spotOrders
				)
				const userData = {
					...state.userProfile,
					userProperties: propsBySpotOrders,
				}
				// сохраняем измененные данные в LS
				saveDataToLocalStorage(USER_DATA_STORAGE, userData)
				startModalAlert()
				return {
					...state,
					messagePopup: {
						category: STYLES.SUCCESS,
						message: action.result.message,
					},
					userProfile: userData,
					// currentCourses: action.result.tickers,
					loading: false,
					loaded: true,
				}
			} else {
				startModalAlert()
				return {
					...state,
					messagePopup: {
						category: STYLES.ERROR,
						message: action.result.message,
					},
					loading: false,
					loaded: true,
				}
			}

		case "CHANGE_ADV_STATUS_ACTION":
			const exchangeName = action.exchange
			const merchantAdvs = getUserPropertyByExchange(
				"merchantAdvs",
				exchangeName,
				state.userProfile.userProperties
			)
			const merchantAdvsUPD = changeAdvStatus(
				exchangeName,
				merchantAdvs,
				action.result.arrayAdvNumbers,
				action.result.advStatus
			)
			const userData = {
				...state.userProfile,
				userProperties: handlerProperties(
					exchangeName,
					state.userProfile.userProperties,
					[],
					"merchantAdvs",
					merchantAdvsUPD
				),
			}
			// сохраняем измененные данные в LS
			saveDataToLocalStorage(USER_DATA_STORAGE, userData)
			return {
				...state,
				userProfile: userData,
				loading: false,
				loaded: true,
			}

		case "GET_EDITABLE_ADV_ACTION":
			if (action.result.success) {
				// console.log(action.result)
				const exchangeName = action.exchange
				const postfix = exchangeName === "Binance" ? "BN" : "PX"
				$(`#modal-editAdv_${postfix}`).modal("show")
				const { userProperties } = state.userProfile
				const currentBalances = getUserPropertyByExchange(
					"currentBalances",
					exchangeName,
					userProperties
				)
				const currentBalancesUPD = {
					...currentBalances,
					p2pBalance: action.result.p2pBalance,
				}
				const userPropsByMerchantPayMethods = handlerProperties(
					exchangeName,
					userProperties,
					[],
					"merchantPayMethods",
					action.result.userPayMethods
				)
				const userPropsByCurrentBalances = handlerProperties(
					exchangeName,
					userPropsByMerchantPayMethods,
					[],
					"currentBalances",
					currentBalancesUPD
				)
				const userData = {
					...state.userProfile,
					userProperties: userPropsByCurrentBalances,
				}
				// сохраняем измененные данные в LS
				saveDataToLocalStorage(USER_DATA_STORAGE, userData)
				// startModalAlert()
				return {
					...state,
					messagePopup: {
						category: STYLES.SUCCESS,
						message: action.result.message,
					},
					userProfile: userData,
					filterDetails: {
						...state.filterDetails,
						advDetails: {
							...action.result.advDetails,
							cleanedAmount:
								+parseFloat(action.result.advDetails.initAmount) -
								+parseFloat(action.result.advDetails.surplusAmount),
							basePrice:
								(action.result.advDetails.price * 100) /
								action.result.advDetails.priceFloatingRatio,
						},
					},
					// advDetails: {
					// 	...action.result.advDetails,
					// 	cleanedAmount:
					// 		+parseFloat(action.result.advDetails.initAmount) -
					// 		+parseFloat(action.result.advDetails.surplusAmount),
					// 	basePrice:
					// 		(action.result.advDetails.price * 100) /
					// 		action.result.advDetails.priceFloatingRatio,
					// },
					// currentCourses: action.result.tickers,
					loading: false,
					loaded: true,
				}
			} else {
				startModalAlert()
				return {
					...state,
					messagePopup: {
						category: STYLES.ERROR,
						message: action.result.message,
					},
					loading: false,
					loaded: true,
				}
			}

		case "GET_EDITABLE_ORDER_ACTION":
			if (action.result.success) {
				$(`#modal-editOrder`).modal("show")
				return {
					...state,
					messagePopup: {
						category: STYLES.SUCCESS,
						message: action.result.message,
					},
					// payTypesList: action.result.payTypes,
					// currentCourses: action.result.tickers,
					filterDetails: {
						...state.filterDetails,
						orderDetails: action.result.orderDetails,
					},
					loading: false,
					loaded: true,
				}
			} else {
				startModalAlert()
				return {
					...state,
					messagePopup: {
						category: STYLES.ERROR,
						message: action.result.message,
					},
					loading: false,
					loaded: true,
				}
			}

		case "UPDATE_ADV_ACTION":
			if (action.result.success) {
				const tickers = action.result.data.tickers
				const merchantAdvs = action.result.data.merchantAdvs
				const p2pOrders = action.result.data.p2pOrders
				const exchangeName = action.exchange
				const { properties } = state.filterDetails
				const { userProperties } = state.userProfile
				const tickerAssetFiat = getUserPropertyByExchange(
					"tickerAssetFiat",
					exchangeName,
					properties
				)
				const tickerCurrencyUSDT = getUserPropertyByExchange(
					"tickerCurrencyUSDT",
					exchangeName,
					properties
				)
				const priceAssetFiat = handlerPriceTickers(tickerAssetFiat, tickers)
				const priceCurrencyUSDT = handlerPriceTickers(
					tickerCurrencyUSDT,
					tickers
				)
				const propsByPriceAssetFiat = handlerProperties(
					exchangeName,
					properties,
					[],
					"priceAssetFiat",
					priceAssetFiat
				)
				const propsByPriceCurrencyUSDT = handlerProperties(
					exchangeName,
					propsByPriceAssetFiat,
					[],
					"priceCurrencyUSDT",
					priceCurrencyUSDT
				)
				const userPropsByMerchantAdvs = handlerProperties(
					exchangeName,
					userProperties,
					[],
					"merchantAdvs",
					merchantAdvs
				)
				const userData = {
					...state.userProfile,
					userProperties: handlerProperties(
						exchangeName,
						userPropsByMerchantAdvs,
						[],
						"p2pOrders",
						p2pOrders
					),
				}
				// сохраняем измененные данные в LS
				saveDataToLocalStorage(USER_DATA_STORAGE, userData)
				startModalAlert()
				return {
					...state,
					loading: false,
					loaded: true,
					// currentCourses: tickers,
					userProfile: userData,
					filterDetails: {
						...state.filterDetails,
						properties: propsByPriceCurrencyUSDT,
					},
					messagePopup: {
						category: STYLES.SUCCESS,
						message: action.result.message,
					},
				}
			} else {
				startModalAlert()
				return {
					...state,
					loading: false,
					loaded: true,
					messagePopup: {
						category: STYLES.ERROR,
						message: action.result.message,
					},
				}
			}

		case "UPDATE_ITEM_ACTION":
			// console.log(action.result)
			const { itemFlag, success, message } = action.result
			if (success) {
				// получаение существующего хранилища констант
				const dataConstants = getDataFromLocalStorage(CONSTANTS_STORAGE)
				if (itemFlag === "exchangeItem") {
					// сохранение изменвшихся полей хранилища констант
					saveDataToLocalStorage(CONSTANTS_STORAGE, {
						...dataConstants,
						exchanges: action.result.exchanges,
					})
				} else if (itemFlag === "currencyItem") {
					// сохранение изменвшихся полей хранилища констант
					saveDataToLocalStorage(CONSTANTS_STORAGE, {
						...dataConstants,
						currencies: action.result.currencies,
					})
				} else if (itemFlag === "paymentItem") {
					// сохранение изменвшихся полей хранилища констант
					saveDataToLocalStorage(CONSTANTS_STORAGE, {
						...dataConstants,
						payTypes: action.result.payTypes,
					})
				} else if (itemFlag === "statusItem") {
					// сохранение изменвшихся полей хранилища констант
					saveDataToLocalStorage(CONSTANTS_STORAGE, {
						...dataConstants,
						statuses: action.result.statuses,
					})
				}
				startModalAlert()
				const dataReports = {
					...state.reports,
					reportMerchantOrders:
						itemFlag === "orderItem"
							? handlerItems(state, action.result.itemDetails, "orderItem")
							: state.reports.reportMerchantOrders,
				}
				// сохранение изменвшихся полей хранилища отчетов
				saveDataToLocalStorage(REPORTS_STORAGE, dataReports)
				return {
					...state,
					messagePopup: {
						category: STYLES.SUCCESS,
						message,
					},
					reports: dataReports,
					loading: false,
					loaded: true,
				}
			} else {
				startModalAlert()
				return {
					...state,
					loading: false,
					loaded: true,
					messagePopup: {
						category: STYLES.ERROR,
						message,
					},
				}
			}

		case "GET_MERCHANT_DETAILS_ACTION":
			if (action.result.success) {
				// извлекаем существующие данные из LS
				const userData = getDataFromLocalStorage(USER_DATA_STORAGE)
				// изменяем данные
				const newUserData = {
					...userData,
					userProperties: updateFavorites(state, action.result.data),
				}
				// сохраняем измененные данные в LS
				saveDataToLocalStorage(USER_DATA_STORAGE, newUserData)
				// startModalAlert()
				return {
					...state,
					loading: false,
					loaded: true,
					userProfile: {
						...state.userProfile,
						userProperties: updateFavorites(state, action.result.data),
					},
					messagePopup: {
						category: STYLES.SUCCESS,
						message: action.result.message,
					},
				}
			} else {
				startModalAlert()
				return {
					...state,
					loading: false,
					loaded: true,
					messagePopup: {
						category: STYLES.ERROR,
						message: action.result.message,
					},
				}
			}

		case "HANDLER_VALUE_FILTER_ACTION":
			return {
				...state,
				filterDetails: handlerFilterDetails(
					state,
					action.exchange,
					action.name,
					action.value
				),
			}

		case "HANDLER_ADV_DETAILS_ACTION":
			return {
				...state,
				filterDetails: {
					...state.filterDetails,
					advDetails: handlerAdvDetails(state, action.name, action.value),
				},
			}

		case "HANDLER_USER_PROFILE_ACTION":
			return {
				...state,
				userProfile: handlerUserProfile(
					state,
					action.exchange,
					action.name,
					action.value
				),
			}

		case "GET_BALANCES_ACTION":
			if (action.result.success) {
				const exchangeName = action.exchange
				const { userProperties } = state.userProfile
				const currentBalances = {
					p2pBalance: action.result.balances.p2pBalance,
					spotBalance: action.result.balances.spotBalance,
					futBalance: action.result.balances.futBalance,
					earnBalance: action.result.balances.earnBalance,
					lockedData: action.result.balances.lockedData,
				}
				const propsByCurrentBalances = handlerProperties(
					exchangeName,
					userProperties,
					[],
					"currentBalances",
					currentBalances
				)
				const userData = {
					...state.userProfile,
					userProperties: propsByCurrentBalances,
				}
				// сохраняем измененные данные в LS
				saveDataToLocalStorage(USER_DATA_STORAGE, userData)
				startModalAlert()
				return {
					...state,
					userProfile: userData,
					messagePopup: {
						category: STYLES.SUCCESS,
						message: action.result.message,
					},
					loading: false,
					loaded: true,
				}
			} else {
				startModalAlert()
				return {
					...state,
					loading: false,
					loaded: true,
					messagePopup: {
						category: STYLES.ERROR,
						message: action.result.message,
					},
				}
			}

		case "GET_DATA_TICKERS_ACTION":
			if (action.result.success) {
				startModalAlert()
				return {
					...state,
					messagePopup: {
						category: STYLES.SUCCESS,
						message: action.result.message,
					},
					loading: false,
					loaded: true,
				}
			} else {
				startModalAlert()
				return {
					...state,
					loading: false,
					loaded: true,
					messagePopup: {
						category: STYLES.ERROR,
						message: action.result.message,
					},
				}
			}

		case "GET_FUNDING_RATES_ACTION":
			if (action.result.success) {
				// console.log(action.result.data.length)
				startModalAlert()
				return {
					...state,
					messagePopup: {
						category: STYLES.SUCCESS,
						message: action.result.message,
					},
					fundingRates: action.result.data,
					loading: false,
					loaded: true,
				}
			} else {
				startModalAlert()
				return {
					...state,
					loading: false,
					loaded: true,
					messagePopup: {
						category: STYLES.ERROR,
						message: action.result.message,
					},
				}
			}

		case "GET_SPREADS_ACTION":
			if (action.result.success) {
				// console.log(action.result)
				let n = 1
				startModalAlert()
				return {
					...state,
					messagePopup: {
						category: STYLES.SUCCESS,
						message: action.result.message,
					},
					spreads: action.result.data.map((item:any)=>{
						return {
							...item,
							itemId: n++
						}
					}),
					loading: false,
					loaded: true,
				}
			} else {
				startModalAlert()
				return {
					...state,
					loading: false,
					loaded: true,
					messagePopup: {
						category: STYLES.ERROR,
						message: action.result.message,
					},
				}
			}

		case "SAVE_SPREADS_ACTION":
			if (action.result.success) {
				startModalAlert()
				return {
					...state,
					messagePopup: {
						category: STYLES.SUCCESS,
						message: action.result.message,
					},
					loading: false,
					loaded: true,
				}
			} else {
				startModalAlert()
				return {
					...state,
					loading: false,
					loaded: true,
					messagePopup: {
						category: STYLES.ERROR,
						message: action.result.message,
					},
				}
			}

		case "TRANSFER_ASSET_ACTION":
			if (action.result.success) {
				const { activeExchange } = state.filterDetails
				const { userProperties } = state.userProfile
				const currentBalances = {
					p2pBalance: action.result.balances.p2pBalance,
					spotBalance: action.result.balances.spotBalance,
					futBalance: action.result.balances.futBalance,
				}
				const propsByCurrentBalances = handlerProperties(
					activeExchange,
					userProperties,
					[],
					"currentBalances",
					currentBalances
				)
				startModalAlert()
				return {
					...state,
					userProfile: {
						...state.userProfile,
						userProperties: propsByCurrentBalances,
					},
					// currentCourses: action.result.tickers,
					messagePopup: {
						category: STYLES.SUCCESS,
						message: action.result.message,
					},
					loading: false,
					loaded: true,
				}
			} else {
				startModalAlert()
				return {
					...state,
					loading: false,
					loaded: true,
					messagePopup: {
						category: STYLES.ERROR,
						message: action.result.message,
					},
				}
			}

		case "CHECK_STATUS_ORDERS_ACTION":
			console.log(
				`+++ ${new Date().toLocaleString()} | Unpaid + Paid orders: ${
					action.result.unpaidOrders
				} +++`
			)
			if (action.result.unpaidOrders !== 0) startModalAlert()
			return {
				...state,
				userOrderStatuses: action.result.userOrderStatuses,
				messagePopup: {
					category: STYLES.SUCCESS,
					message: action.result.message,
				},
				loading: false,
				loaded: true,
			}

		case "CREATE_NEW_USER_ACTION":
			if (action.result.success) {
				const userData = {
					...state.userProfile,
					auth: true,
					token: action.result.token,
					id: action.result.user.id,
					login: action.result.user.login,
					lang: action.result.user.lang,
					theme: action.result.user.theme,
					status: action.result.user.status,
					advSell: action.result.user.advSell,
					userProperties: action.result.user.properties,
				}
				const constants = {
					tickers: action.result.tickers,
					payTypes: action.result.payTypes,
					exchanges: action.result.exchanges,
					currencies: action.result.currencies,
					statuses: action.result.statuses,
				}
				saveDataToLocalStorage(USER_DATA_STORAGE, userData)
				saveDataToLocalStorage(CONSTANTS_STORAGE, constants)
				startModalAlert()
				return {
					...state,
					currentCourses: action.result.tickers,
					payTypesList: action.result.payTypes,
					userProfile: userData,
					messagePopup: {
						category: STYLES.SUCCESS,
						message: action.result.message,
					},
					loading: false,
					loaded: true,
				}
			}
			// action.result.success !== "true"
			else {
				startModalAlert()
				return {
					...state,
					loading: false,
					loaded: true,
					messagePopup: {
						category: STYLES.ERROR,
						message: action.result.message,
					},
				}
			}

		case "UPDATE_USER_ACTION":
			if (action.result.success) {
				// обновляем requestHeader _BZ, _GX в LocalStorage
				// const requestHeaderBZ = {
				// 	token: action.result.user.properties[3].requestHeader.token,
				// 	cookie: action.result.user.properties[3].requestHeader.cookie,
				// 	userAgent: action.result.user.properties[3].requestHeader.userAgent,
				// 	timestamp: new Date().getTime(),
				// }
				// const requestHeaderGX = {
				// 	token: action.result.user.properties[4].requestHeader.token,
				// 	userAgent: action.result.user.properties[4].requestHeader.userAgent,
				// 	timestamp: new Date().getTime(),
				// }
				// saveDataToLocalStorage("requestHeaderBZ", requestHeaderBZ)
				// saveDataToLocalStorage("requestHeaderGX", requestHeaderGX)
				startModalAlert()
				return {
					...state,
					// userProfile: userData,
					messagePopup: {
						category: STYLES.SUCCESS,
						message: action.result.message,
					},
					loading: false,
					loaded: true,
				}
			} else {
				startModalAlert()
				return {
					...state,
					loading: false,
					loaded: true,
					messagePopup: {
						category: STYLES.ERROR,
						message: action.result.message,
					},
				}
			}

		case "RESET_PASSWORD_ACTION":
			startModalAlert()
			return {
				...state,
				messagePopup: {
					category: STYLES.SUCCESS,
					message: action.result.message,
				},
				loading: false,
				loaded: true,
			}

		case "LOGIN_USER_ACTION":
			if (action.result.success) {
				const userData = {
					...state.userProfile,
					auth: true,
					token: action.result.token,
					id: action.result.user.id,
					login: action.result.user.login,
					lang: action.result.user.lang,
					theme: action.result.user.theme,
					status: action.result.user.status,
					subAccounts: action.result.user.subAccounts,
					advSell: action.result.user.advSell,
					userProperties: action.result.user.properties,
				}
				const constants = {
					tickers: action.result.tickers,
					payTypes: action.result.payTypes,
					exchanges: action.result.exchanges,
					currencies: action.result.currencies,
					statuses: action.result.statuses,
				}
				saveDataToLocalStorage(USER_DATA_STORAGE, userData)
				saveDataToLocalStorage(CONSTANTS_STORAGE, constants)
				return {
					...state,
					currentCourses: action.result.tickers,
					payTypesList: action.result.payTypes,
					userProfile: userData,
					filterDetails: getModifiedPayTypeDetails(
						userData.userProperties,
						state.filterDetails
					),
					messagePopup: {
						category: STYLES.SUCCESS,
						message: action.result.message,
					},
					loading: false,
					loaded: true,
				}
			} else {
				startModalAlert()
				return {
					...state,
					loading: false,
					loaded: true,
					messagePopup: {
						category: STYLES.ERROR,
						message: action.result.message,
					},
				}
			}

		case "LOGOUT_USER_ACTION":
			if (action.result.success) {
				const userData = {
					...state.userProfile,
					auth: false,
					id: "",
					token: "",
					status: "",
					login: "",
				}
				// removeDataFromLocalStorage(USER_DATA_STORAGE)
				// removeDataFromLocalStorage(HEADER_LOCAL_STORAGE)
				saveDataToLocalStorage(USER_DATA_STORAGE, userData)
				startModalAlert()
				// Открываем стартовую заставку
				setActiveMainPage()
				return {
					...state,
					// userProfile: userData,
					messagePopup: {
						category: STYLES.SUCCESS,
						message: action.result.message,
					},
					loading: false,
					loaded: true,
				}
			}
			// action.result.success !== "true"
			else {
				startModalAlert()
				return {
					...state,
					messagePopup: {
						category: STYLES.ERROR,
						message: action.result.message,
					},
					loading: false,
					loaded: true,
				}
			}

		case "HANDLER_POPUP_WINDOW_ACTION":
			return {
				...state,
				messagePopup: {
					category: action.category,
					message: action.message,
				},
			}

		case "ADD_NEW_ITEM_ACTION":
			// получаение существующего хранилища констант
			const dataConstants = getDataFromLocalStorage(CONSTANTS_STORAGE)
			// сохранение изменвшихся полей хранилища констант
			saveDataToLocalStorage(CONSTANTS_STORAGE, {
				...dataConstants,
				payTypes: action.result.payTypes,
				exchanges: action.result.exchanges,
				currencies: action.result.currencies,
			})
			startModalAlert()
			return {
				...state,
				messagePopup: {
					category: action.result.success ? STYLES.SUCCESS : STYLES.ERROR,
					message: action.result.message,
				},
				loading: false,
				loaded: true,
			}

		case "INSERT_ORDER_TO_DB_ACTION":
			startModalAlert()
			return {
				...state,
				messagePopup: {
					category: action.result.success ? STYLES.SUCCESS : STYLES.ERROR,
					message: action.result.message,
				},
				loading: false,
				loaded: true,
			}

		case "GET_DATA_REPORT_ACTION":
			// console.log(action.result)
			startModalAlert()
			if (action.result.success) {
				// получаение существующего хранилища констант
				const dataConstants = getDataFromLocalStorage(CONSTANTS_STORAGE)
				// сохранение изменвшихся полей хранилища констант
				saveDataToLocalStorage(CONSTANTS_STORAGE, {
					...dataConstants,
					tickers: action.result.tickers,
				})
				const dataReports = {
					reportMerchantOrders: action.result.reportMerchantOrders,
					reportSpotOrders: action.result.reportSpotOrders,
					reportBalances: action.result.reportBalances,
					reportCost: action.result.reportCost,
					reportStats: {
						monthStats:
							action.result.reportStats.monthStats.buy.length === 0
								? state.reports.reportStats.monthStats
								: action.result.reportStats.monthStats,
						yearStatsV1:
							action.result.reportStats.yearStatsV1.buy.length === 0
								? state.reports.reportStats.yearStatsV1
								: action.result.reportStats.yearStatsV1,
						yearStatsV2:
							action.result.reportStats.yearStatsV2.buy.length === 0
								? state.reports.reportStats.yearStatsV2
								: action.result.reportStats.yearStatsV2,
						yearStatsV3:
							action.result.reportStats.yearStatsV3.buy.length === 0
								? state.reports.reportStats.yearStatsV3
								: action.result.reportStats.yearStatsV3,
					},
				}
				// сохранение изменвшихся полей хранилища отчетов
				saveDataToLocalStorage(REPORTS_STORAGE, dataReports)
				return {
					...state,
					reports: dataReports,
					messagePopup: {
						category: STYLES.SUCCESS,
						message: action.result.message,
					},
					loading: false,
					loaded: true,
				}
			} else {
				return {
					...state,
					messagePopup: {
						category: STYLES.ERROR,
						message: action.result.message,
					},
					loading: false,
					loaded: true,
				}
			}

		case "GET_GROUP_ITEMS_ACTION":
			if (action.result.success) {
				let userProps = state.userProfile.userProperties.slice()
				if (action.typeItems === "allOtcOrders") {
					const orders = action.result.orders.slice()
					for (let i = 0; i < orders.length; i++) {
						userProps = handlerProperties(
							orders[i].exchangeId,
							userProps,
							[],
							"merchantOrders",
							orders[i].orders
						)
					}
				} else if (action.typeItems === "allBalances") {
					const balances = action.result.balances.slice()
					for (let i = 0; i < balances.length; i++) {
						const currentBalances = {
							spotBalance: balances[i].balances.spotBalance,
							p2pBalance: balances[i].balances.p2pBalance,
							futBalance: balances[i].balances.futBalance,
							earnBalance: balances[i].balances.earnBalance,
							lockedData: balances[i].balances.lockedData,
						}
						userProps = handlerProperties(
							balances[i].exchangeId,
							userProps,
							[],
							"currentBalances",
							currentBalances
						)
					}
					// получаение существующего хранилища констант
					const dataConstants = getDataFromLocalStorage(CONSTANTS_STORAGE)
					// сохранение изменвшихся полей хранилища констант
					saveDataToLocalStorage(CONSTANTS_STORAGE, {
						...dataConstants,
						tickers: action.result.tickers,
					})
				} else if (action.typeItems === "allAdvs") {
				} else if (action.typeItems === "allActiveSpotOrders") {
					const orders = action.result.orders.slice()
					for (let i = 0; i < orders.length; i++) {
						userProps = handlerProperties(
							orders[i].exchangeId,
							userProps,
							[],
							"spotOrders",
							orders[i].orders
						)
					}
				}

				const userData = {
					...state.userProfile,
					userProperties: userProps,
				}
				// сохраняем измененные данные в LS
				saveDataToLocalStorage(USER_DATA_STORAGE, userData)
				startModalAlert()
				return {
					...state,
					userProfile: userData,
					messagePopup: {
						category: STYLES.SUCCESS,
						message: action.result.message,
					},
					loading: false,
					loaded: true,
				}
			} else {
				return {
					...state,
					messagePopup: {
						category: STYLES.ERROR,
						message: action.result.message,
					},
					loading: false,
					loaded: true,
				}
			}

		default:
			return state
	}
}
